package com.ll.mybatis;

import com.ll.mybatis.dao.EmployeeMapper;
import com.ll.mybatis.dao.EmployeeMapperAnnotation;
import com.ll.mybatis.entity.Employee;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;

/**
 * 1.接口式编程
 *      原生:         Dao ==> DaoImpl
 *      mybatis:     EmployeeMapper ==> EmployeeMapper.xml
 *
 * 2.sqlSession代表和数据库的一次会话,用完必须关闭
 *
 * 3.sqlSession和connection一样,都是非线程安全,每次使用都应该去获取新的对象
 *
 * 4.EmployeeMapper接口没有实现类,但是mybatis会为这个接口生成一个代理对象
 *      (将接口和xml文件进行绑定)
 *      EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
 *
 *  5.两个重要的配置文件
 *          mybatis-config.xml:包含数据库连接池信息,事物管理信息等
 *
 *          <select id="getEmployeeById" resultType="com.ll.mybatis.entity.Employee">
 *              select id, last_name, email, gender  from tbl_employee where id = #{id}
 *          </select>
 *          EmployeeMapper.xml: sql映射文件
 *
 * @author 刘龙
 * @version 1.0
 */
public class MybatisInterface {

    public SqlSessionFactory getsqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        return new SqlSessionFactoryBuilder().build(inputStream);
    }

    /**
     * 查找
     */
    @Test
    public void getEmpByMapperClass() throws IOException {
        SqlSession sqlSession = getsqlSessionFactory().openSession();

        Employee employeeById;
        try {
            EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);

            // mybatis会为接口自动创建一个代理对象,代理对象进行增删改查
            // class com.sun.proxy.$Proxy9
            System.out.println(mapper.getClass());

            employeeById = mapper.getEmployeeById(4);
        } finally {
            sqlSession.close();
        }

        System.out.println(employeeById);
    }

    /**
     * 基于注解
     */
    @Test
    public void test() throws IOException {
        SqlSession sqlSession = getsqlSessionFactory().openSession();

        Employee employeeById;
        try {
            /*
            *       @Select("select id from tbl_employee where id=#{id}")
                    public Employee getEmployeeById(Integer id);
            * */
            EmployeeMapperAnnotation mapper = sqlSession.getMapper(EmployeeMapperAnnotation.class);


            employeeById = mapper.getEmployeeById(4);
        } finally {
            sqlSession.close();
        }

        System.out.println(employeeById);
    }
}
